<!--
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-04-13 17:49:37
 * @LastEditTime: 2022-05-20 20:58:08
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description:Excel 导出
-->
<template>
  <el-dialog :title="$t('excel.title')" :model-value="modelValue" @close="closed" width="30%">
    <el-input v-model="excelName" :placeholder="$t('excel.placeholder')"></el-input>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closed">{{ $t('excel.close') }}</el-button>
        <el-button type="primary" @click="onConfirm" :loading="loading">{{
          $t('excel.confirm')
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { watchSwitchLang } from '@/utils/i18n'
import { getUserManageAllList } from '@/api/user-manager'
import { USER_RELATIONS, formatJson } from './Export2ExcelConstants'
// eslint-disable-next-line no-undef
defineProps({
  modelValue: {
    type: Boolean,
    required: true
  }
})
const i18n = useI18n()
const excelName = ref('')
let exportDefaultName = i18n.t('msg.excel.defaultName')

excelName.value = i18n.t('excel.defaultName')
watchSwitchLang(() => {
  exportDefaultName = i18n.t('msg.excel.defaultName')

  excelName.value = i18n.t('excel.defaultName')
})
// eslint-disable-next-line no-undef
const emits = defineEmits(['update:modelValue'])

/**
 * 导出按钮点击事件
 */
const loading = ref(false)
const onConfirm = async () => {
  loading.value = true
  const { list } = await getUserManageAllList()

  const data = formatJson(USER_RELATIONS, list)

  const excel = await import('@/utils/Export2Excel')
  excel.export_json_to_excel({
    // excel 表头
    header: Object.keys(USER_RELATIONS),
    // excel 数据（二维数组结构）
    data,
    // 文件名称
    filename: excelName.value || exportDefaultName,
    // 是否自动列宽
    autoWidth: true,
    // 文件类型
    bookType: 'xlsx'
  })
  closed()
}

/**
 * 关闭
 */
const closed = () => {
  loading.value = false
  emits('update:modelValue', false)
}
</script>
<style scoped lang="scss">
</style>
